<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/26 16:08
 */

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Controllers\ModelForm;
use App\Http\Models\GoodsCorrection;
use App\Http\Models\StatisticsUserKill;
use App\Http\Models\GoodsAudit;
use App\Http\Models\StatisticsGoodsToday;
use App\Http\Models\UserIntegralLog;
use App\Http\Models\Goods;
use Auth;
use DB;
use Illuminate\Http\Request;
use function Sodium\crypto_box_publickey_from_secretkey;
use Illuminate\Support\MessageBag;
use App\Admin\Extensions\CheckRowEdit;
use App\Http\Controllers\Controller;
use Encore\Admin\Widgets\Table;

class GoodsCorrectionController extends Controller
{
    use ModelForm;
    protected $headerStr = '纠错';
    protected $type_ = '';
    protected $is_today;

    public function show($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header($this->headerStr . '管理');
            $content->body($this->form()->edit($id));
        });
    }

    public function index()
    {
        $this->is_today = request('today');
        $this->type_ = request('t') ?: '';
        return Admin::content(function (Content $content) {
            $content->header($this->headerStr . '管理');
            $content->description(show_description_error($this->type_, $this->is_today));
            $content->body($this->grid());
        });
    }


    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header($this->headerStr . '管理');
            $content->body($this->form()->edit($id));
        });
    }


    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header($this->headerStr . '管理');
            $content->description();
            $content->body($this->form());
        });
    }


    protected function grid()
    {
        return Admin::grid(GoodsCorrection::class, function (Grid $grid) {
            $type = $this->type_;
            $status = !empty($type) && $type == 'already' ? [1] : [0];
            if (!empty($type) && $type == 'already' || empty($type)) {
                if ($this->is_today) {
                    $grid->model()
                        ->select('goods.goodslink', 'goods_correction.gid as goods_id', 'goods.goodsid', 'goods_coupon.couponmoney', 'goods_coupon.couponlink', 'goods.commissionrate', 'goods.commissiontype', 'goods.commissiontype', 'goods.begintimetype', 'goods.begintime', 'goods.origprice', 'goods.voucherprice', 'goods_correction.id', 'goods_correction.userid', 'goods_correction.gid', 'goods_correction.is_auto', 'goods.goodstype', 'users.name', 'goods_correction.content', 'goods_correction.state', 'goods.goodstitle', 'goods.coverimage', 'goods_correction.type', 'goods_correction.created_at', 'goods_correction.updated_at')
                        ->leftjoin('goods', 'goods.id', '=', 'goods_correction.gid')
                        ->leftjoin('users', 'users.id', '=', 'goods_correction.userid')
                        ->leftjoin('goods_coupon', 'goods_coupon.gid', '=', 'goods_correction.gid')
                        ->whereIn('goods_correction.state', $status)
                        ->whereDate('goods_correction.updated_at', date('Y-m-d'))
                        ->orderBy('goods_correction.created_at', 'desc');
                } else {
                    $grid->model()
                        ->select('goods.goodslink', 'goods_correction.gid as goods_id', 'goods.goodsid', 'goods_coupon.couponmoney', 'goods_coupon.couponlink', 'goods.commissionrate', 'goods.commissiontype', 'goods.commissiontype', 'goods.begintimetype', 'goods.begintime', 'goods.origprice', 'goods.voucherprice', 'goods_correction.id', 'goods_correction.userid', 'goods_correction.gid', 'goods_correction.is_auto', 'goods.goodstype', 'users.name', 'goods_correction.content', 'goods_correction.state', 'goods.goodstitle', 'goods.coverimage', 'goods_correction.type', 'goods_correction.created_at', 'goods_correction.updated_at')
                        ->leftjoin('goods', 'goods.id', '=', 'goods_correction.gid')
                        ->leftjoin('users', 'users.id', '=', 'goods_correction.userid')
                        ->leftjoin('goods_coupon', 'goods_coupon.gid', '=', 'goods_correction.gid')
                        ->whereIn('goods_correction.state', $status)
                        ->orderBy('goods_correction.created_at', 'desc');
                }
            } elseif (!empty($type) && $type == 'today_not') {
                $grid->model()
                    ->select('goods_coupon.couponmoney', 'goods_correction.gid as goods_id', 'goods.goodsid', 'goods_coupon.couponlink', 'goods.commissionrate', 'goods.commissiontype', 'goods.commissiontype', 'goods.goodslink', 'goods.begintime', 'goods.begintimetype', 'goods.origprice', 'goods.voucherprice', 'goods_correction.id', 'goods_correction.userid', 'goods_correction.gid', 'goods_correction.is_auto', 'goods.goodstype', 'users.name', 'goods_correction.content', 'goods_correction.state', 'goods.goodstitle', 'goods.coverimage', 'goods_correction.type', 'goods_correction.created_at', 'goods_correction.updated_at')
                    ->leftjoin('goods', 'goods.id', '=', 'goods_correction.gid')
                    ->leftjoin('users', 'users.id', '=', 'goods_correction.userid')
                    ->leftjoin('goods_coupon', 'goods_coupon.gid', '=', 'goods_correction.gid')
                    ->whereIn('goods_correction.state', $status)
                    ->whereDate('goods_correction.created_at', date('Y-m-d', time()))
                    ->orderBy('goods_correction.created_at', 'desc');
            }
            $grid->id('ID')->sortable();
            $grid->coverimage('主封面图')->display(function ($pictures) {
                $url = to_json_array($pictures)[0];
                return '<img src="' . $url . '" width="120" height="120" data-url=1 class="image_show" style="margin-left:5px" onclick=showimage(' . $this->gid . ',"' . $url . '")>';
                // return '<img src="' . $url . '" width="50" height="50">';
            });

            $grid->goodstitle('商品信息')->display(function () {
                // $couponinfo = GoodsCoupon::getGoodsCouponlink($this->id);
                $commissioninfo = commissionrateInfo($this->commissiontype, $this->commissionrate);

                $info = array
                (
                    '商品标题' => '<a target="_blank" href="' . $this->goodslink . '">' . str_limit($this->goodstitle, $limit = 30, $end = '...') . '</a>',
                    '原价/券后价' => '￥' . $this->origprice . ' / ￥' . $this->voucherprice,
                    '优惠券信息' => $this->couponlink ? '<a target="_blank" href="' . $this->couponlink . '">￥ ' . $this->couponmoney . '</a>' : '',
                    '佣金信息' => $commissioninfo,
                    '商品id' => $this->goods_id,
                );
                return new Table([], $info);
            });

            // $grid->goodstitle('商品标题')->display(function ($value) {
            //     // return str_limit($value, $limit = 25, $end = '...');
            //     return '<a target="_blank" href="' . $this->goodslink . '">' . str_limit($value, $limit = 30, $end = '...') . '</a>';

            // });
            // $grid->voucherprice('原价 / 券后价')->display(function ($value) {
            //     return '￥' . $this->origprice . ' / ￥' . $value;
            // });
            // $grid->couponmoney('优惠券信息')->display(function ($value) {
            //     return '<a target="_blank" href="' . $this->couponlink . '">￥' . $value . '</a>';
            // });
            $grid->begintime('开始时间')->display(function ($value) {
                return $this->begintimetype == 1 ? '立即开始' : $value;
            });

            // $grid->commissiontype('佣金信息')->display(function () {
            //     return commissionrateInfo($this->commissiontype, $this->commissionrate);
            // });

            $grid->type('纠错类型')->display(function ($value) {
                // dd($value);
                return GoodsCorrection::get_type()[$value];
            });
            // $grid->userid('用户ID(昵称)')->display(function () {
            //     return $this->userid . '(' . $this->name . ')';
            // });
            $grid->userid('提交人(ID)')->display(function () {
                return $this->name . '(' . $this->userid . ')';
            });
            $grid->is_auto('人工/机器')->display(function ($value) {
                return $value == 1 ? '<span class="label label-default">机械纠错</span>' : '<span class="label label-primary">人工纠错</span>';
            });

            // $grid->updated_at('纠错时间')->sortable();
            $grid->state('纠错状态')->display(function ($value) {
                if ($value == 1) {
                    $str = '<span class=" label label-success">已纠错</span>';
                } else {
                    $str = '<span class=" label label-warning">未纠错</span>';
                }
                return $str;
            });
            $grid->content('问题描述')->display(function ($value) {
                return str_limit($value, $limit = 25, $end = '...');
            });
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();//禁用查询过滤器
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('is_auto', '人工/机器')->select([0 => '人工纠错', '1' => '机器纠错']);
                    $filter->equal('type', '纠错类型')->select(GoodsCorrection::get_type());
                    $filter->like('goodstitle', '商品标题');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('goodsid', '淘宝商品ID');
                    $filter->where(function ($query) {
                        $query->whereRaw("`goods_correction`.`gid` ={$this->input}");
                    }, '内部商品ID');
                });
            });
            $grid->created_at('提交时间')->sortable();
            if (empty($this->type_)|| $this->type_=='today_not') {
                $grid->actions(function ($actions) {//|| Admin::user()->isRole('operator')
                    if (Admin::user()->isRole('administrator') || Admin::user()->isRole('goodscorrection')) {
                        $actions->disableEdit();
                        if ($actions->row['goodstype'] == 1) {   //爆款
                            $actions->append("<a href='/admin/bursting/examine/{$actions->row['gid']}/edit?error_id={$actions->row['id']}'><span class='btn btn-success'>编辑</span></a>");
                        } elseif ($actions->row['goodstype'] == 2) {  //秒杀
                            $actions->append("<a href='/admin/kill/manage/{$actions->row['gid']}/edit?error_id={$actions->row['id']}'><span class='btn btn-success'>编辑</span></a>");
                        } elseif ($actions->row['goodstype'] == 0) {   //平推
                            $actions->append("<a href='/admin/goods/unaudited/{$actions->row['gid']}/edit?error_id={$actions->row['id']}'><span class='btn btn-success'>编辑</span></a>");
                        }
                    }
                    $actions->append('<a href="javascript:void(0)" style="margin-left:15px;"  class="btn btn-primary"  title="已纠错" onclick="error_correction(' . $actions->getKey() . ')">纠错</a>');
                    $actions->append('<a href="javascript:void(0)" style="margin-left:15px;"  class="btn btn-danger"  title="删除" onclick="del_error_goods(' . $actions->getKey() . ')">删除</a>');
                    if (method_exists($actions, 'disableView')) {
                        $actions->disableView();
                    }
                    $actions->disableEdit();
                    $actions->disableDelete();
                });
            } else {
                $grid->disableActions();
            }
            //
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->perPages([10, 20, 30, 40, 50]);
            $grid->paginate(env('Admin_Limit'));
        });
    }

    protected function get_data()
    {

    }

    public function state(Request $request)
    {
        foreach (GoodsCorrection::find($request->get('ids')) as $post) {
            $post->state = $request->get('action');
            $post->save();
        }
    }

    protected function form()
    {
        return Admin::form(GoodsCorrection::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->select('state', '审核状态')->options([0 => '未纠错', 1 => '已纠错']);
            $form->select('type', '纠错类型')->options(GoodsCorrection::get_type());
            $form->disableReset();

            $form->tools(function (Form\Tools $tools) {
                $tools->disableBackButton();// 去掉返回按钮
                // $tools->disableListButton(); // 去掉跳转列表按钮
                //$tools->disableDelete(); // 去掉跳转列表按钮
                //$tools->disableView(); // 去掉跳转列表按钮
            });
        });
    }
}